//
//  FilmViewController.m
//  觅影
//
//  Created by lanou on 16/4/15.
//  Copyright © 2016年  陶虹. All rights reserved.
//

#import "FilmViewController.h"
#import "SearchResultViewController.h"
#import "SearchModel.h"
#import "SearchBoxTableViewCell.h"
#import "LibraryDetailViewController.h"
@interface FilmViewController ()<UISearchBarDelegate,UISearchControllerDelegate,UISearchResultsUpdating, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) SearchResultViewController *resultsTableController;

@property (nonatomic, strong) UISearchController *searchController;

// for state restoration
@property (nonatomic, assign) BOOL searchControllerWasActive;
@property (nonatomic, assign) BOOL searchControllerSearchFieldWasFirstResponder;
@property (nonatomic, strong) NSMutableArray *modelArray;

@property (nonatomic, strong) UITableView *filmTableView;

@end

@implementation FilmViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultsTableController];
    // 设置实时搜索刷新代理
    self.searchController.searchResultsUpdater = self;
    // 设置搜索框 自适应
    [self.searchController.searchBar sizeToFit];
    self.searchController.searchBar.placeholder = NSLocalizedString(@"搜索", @"search");
    // 设置搜索代理
    self.searchController.delegate = self;
    // 设置是否有半透明覆盖层 (default is YES 默认是YES)
    self.searchController.dimsBackgroundDuringPresentation = NO;
    // 设置搜索框代理
    self.searchController.searchBar.delegate = self;
    // 设置哪个viewController来显示UISearchViewController的（需要在适当的位置 来添加该代码）
    // a、如果不添加上面这行代码，在设置hidesNavigationBarDuringPresentation这个属性为YES的时候，搜索框进入编辑模式会导致，searchbar不可见，偏移-64;在设置为NO的时候，进入编辑模式输入内容会导致高度为64的白条，猜测是导航栏没有渲染出来
    // b、如果添加了上面这行代码，在设置hidesNavigationBarDuringPresentation这个属性为YES的时候，输入框进入编辑模式正常显示和使用;在设置为NO的时候，搜索框进入编辑模式导致向下偏移64，具体原因暂时未找到
    self.definesPresentationContext = YES;
    self.filmTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, KHEIGHT) style:UITableViewStylePlain];
    self.filmTableView.delegate = self;
    self.filmTableView.dataSource = self;
    self.filmTableView.tableHeaderView = _searchController.searchBar;
    [self.filmTableView registerNib:[UINib nibWithNibName:@"SearchBoxTableViewCell" bundle:nil] forCellReuseIdentifier:@"search"];
    self.modelArray = [NSMutableArray array];
    [self.view addSubview:_filmTableView];
}

#pragma mark - UISearchBarDelegate (which you use ,which you choose!!)
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar                   // return NO to not become first responder
{
    return YES;
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar                    // called when text starts editing
{
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar                       // return NO to not resign first responder
{
    return YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar                     // called when text ends editing
{
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText   // called when text changes (including clear)
{
}
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text NS_AVAILABLE_IOS(3_0) // called before text changes
{
    return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _modelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchBoxTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"search" forIndexPath:indexPath];
    SearchModel *search = self.modelArray[indexPath.row];
    [cell cellConfigureWithsearchModel:search];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_modelArray.count == 0) {
        return 0;
    }
    else{
        return 106;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_modelArray.count != 0) {
        LibraryDetailViewController *libraryVc = [[LibraryDetailViewController alloc]initWithNibName:@"LibraryDetailViewController" bundle:nil];
        SearchModel *introModel = self.modelArray[indexPath.row];
        libraryVc.movieId = [introModel.Id stringValue];
        [self.navigationController pushViewController:libraryVc animated:YES];
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar                    // called when keyboard search button pressed
{
    NSString *searchText = [_searchController.searchBar.text stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    if ([[NetWorkState shareInstance] reachability] == YES) {
        [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/pingping_japi/film/applist?keyword=%@&page=1&page_size=10&type=1", searchText] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSMutableDictionary *resultDic = dic[@"result"];
            NSMutableArray *movieListArray = resultDic[@"movieList"];
            self.modelArray = [NSMutableArray array];
            for (NSMutableDictionary *movieListDic in movieListArray) {
                SearchModel *model = [[SearchModel alloc]init];
                [model setValuesForKeysWithDictionary:movieListDic];
                [self.modelArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.filmTableView reloadData];
            });
        } error:nil];
    }
    else{
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲，麻烦连接网络先" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        });
    }
}
- (void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar                   // called when bookmark button pressed
{
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar                     // called when cancel button pressed
{
}
- (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar NS_AVAILABLE_IOS(3_2) // called when search results button pressed
{
}
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope NS_AVAILABLE_IOS(3_0){
    
}

#pragma mark - UISearchControllerDelegate  (which you use ,which you choose!!)
// These methods are called when automatic presentation or dismissal occurs. They will not be called if you present or dismiss the search controller yourself.
- (void)willPresentSearchController:(UISearchController *)searchController{
    // do something before the search controller is presented
}
- (void)didPresentSearchController:(UISearchController *)searchController{
}
- (void)willDismissSearchController:(UISearchController *)searchController{
}
- (void)didDismissSearchController:(UISearchController *)searchController{
}

// Called after the search controller's search bar has agreed to begin editing or when 'active' is set to YES. If you choose not to present the controller yourself or do not implement this method, a default presentation is performed on your behalf.
- (void)presentSearchController:(UISearchController *)searchController{
    
}
#pragma mark - UISearchResultsUpdating  (which you use ,which you choose!!)
// Called when the search bar's text or scope has changed or when the search bar becomes first responder.
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
